<script setup lang="ts">
import {ref, h, onMounted} from "vue";
import { useReformMainHook } from "./utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {ElMessage, ElTag} from "element-plus";

import Delete from "@iconify-icons/ep/delete";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import { useUserStoreHook } from "@/store/modules/user";
import { CommonUtils } from "@/utils/common";
import ReformMainFormModal from "./reformMain-measure-modal.vue";
import DocumentChecked from "@iconify-icons/ep/document-checked";
import Upload from "@iconify-icons/ep/upload";
import EditPen from "@iconify-icons/ep/edit-pen";
import View from "@iconify-icons/ep/view";
import SetUp from "@iconify-icons/ep/set-up";
import { ReformMainPageResponse } from "@/api/airport/reform/reformMain";
import AddFill from "@iconify-icons/ri/add-circle-line";
import ReformMainDetailModal from "./reformMain-detail-modal.vue";
import ReformMainMeasureModal from "./reformMain-measure-modal.vue";
import {useRoute, useRouter} from 'vue-router'; // 导入路由
import { getDeptTree } from "@/api/system/dept";


// 引入 getInspectionCheckInfoApi 函数
import { getInspectionCheckInfoApi } from "@/api/airport/inspection/inspectionCheck";
// 引入 inspectionCheck-detail-modal 组件
import InspectionCheckDetailModal from "@/views/airport/inspection/inspectionCheck/inspectionCheck-detail-modal.vue";
import InspectionFormModal from "@/views/airport/inspection/inspectionList/inspection-form-modal.vue";


/** 组件name最好和菜单表中的router_name一致 */
defineOptions({
  name: "reformProject"
});

const tableRef = ref();
const searchFormRef = ref();
const router = useRouter(); // 初始化路由
const deptTree = ref([]);

const {
  searchFormParams,
  pageLoading,
  columns, // 直接使用从 hook 中解构出来的 columns
  dataList,
  pagination,
  timeRange,
  defaultSort,
  multipleSelection,
  onSearch,
  resetForm,
  onSortChanged,
  exportAllExcel,
  getReformMainList,
  handleDelete,
  handleBulkDelete,
} = useReformMainHook();

const { hasAdminPermission } = useUserStoreHook();
// 批量删除权限控制处理函数
const handleBulkDeleteWithPermission = (tableRef) => {
  debugger
  if (hasAdminPermission) {
    handleBulkDelete(tableRef);
  } else {
    ElMessage.warning("您没有部门负责人权限");
  }
};

const opType = ref<"add" | "update">("add");
const modalVisible = ref(false);
const opRow = ref<ReformMainPageResponse>();

const route = useRoute(); // 初始化路由

onMounted(async () => {
  try {
    // 新增：获取部门树数据
    const { data } = await getDeptTree();
    if (data) {
      // 转换数据格式为级联选择器所需格式
      const convertDeptTree = (nodes) => {
        return nodes.map(node => ({
          value: node.id,
          label: node.label,
          children: node.children ? convertDeptTree(node.children) : undefined
        }));
      };
      deptTree.value = Array.isArray(data) ? convertDeptTree(data) : convertDeptTree([data]);
    }
  } catch (error) {
    console.error('获取部门树数据失败:', error);
  }
});

function openDialog(type: "add" | "update", row?: ReformMainPageResponse) {
  opType.value = type;
  opRow.value = row;
  modalVisible.value = true;
}
// 新增变量控制 inspectionCheck 详情弹窗
const inspectionCheckDetailVisible = ref(false);
const inspectionCheckDetailData = ref(null);
const detailVisible = ref(false);
const detailRow = ref<ReformMainPageResponse>();

function openDetail(row: ReformMainPageResponse) {
  if (row.inspectionCheckId) {
    openInspectionCheckDetail(row.inspectionCheckId);
  } else {
    openReformDetail(row);
  }
}

const code = route.query.code;
if (code) {
  searchFormParams.code = route.query.code as string;
}



function handleSafetyInfoClick(relatedQuestionId: number) {
  router.push({
    path: '/airport/safetyManage/reportList/index',
    query: { reportId: relatedQuestionId }
  });
}


function openReformDetail(row: ReformMainPageResponse) {
  detailRow.value = row;
  detailVisible.value = true;
}

function openMeasureModal(row: ReformMainPageResponse) {
  opType.value = "update";
  opRow.value = row;
  modalVisible.value = true;
}

// 添加HTML标签处理函数：将图片标签替换为文本，移除其他所有HTML标签
function stripHtmlTagsExceptImages(html: string): string {
  if (!html) return "";
  // 1. 将所有img标签替换为"《点击查看图片》"
  // 2. 移除所有其他HTML标签
  return html
    .replace(/<img[^>]*>/gi, '《点击查看图片》')  // 替换图片标签
    .replace(/<[^>]+>/g, '');  // 移除剩余HTML标签
}

// 打开 inspectionCheck 详情弹窗
async function openInspectionCheckDetail(inspectionCheckId: number) {
  try {
    const { data } = await getInspectionCheckInfoApi(inspectionCheckId);
    inspectionCheckDetailData.value = data;
    inspectionCheckDetailVisible.value = true;
  } catch (error) {
    console.error('获取检查项详情失败', error);
    ElMessage.error('获取检查项详情失败，请重试');
  }
}

// 添加重置处理函数
async function handleReset() {
  // 1. 调用原有的重置表单方法
  resetForm(searchFormRef, tableRef);

  // 2. 清除URL中的reportId参数
  if (route.query.code) {
    const {code, ...otherQuery} = route.query;
    router.replace({
      path: route.path,
      query: Object.keys(otherQuery).length ? otherQuery : undefined
    });
  }

  // 3. 重置后刷新表格数据
  await getReformMainList();
}

</script>

<template>
  <div class="main">
    <!-- 搜索栏 -->
    <el-form
      ref="searchFormRef"
      :inline="true"
      :model="searchFormParams"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
    >
      <el-form-item label="整改通知书编号" prop="code">
        <el-input
          v-model="searchFormParams.code"
          placeholder="请输入整改通知书编号"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="整改督察员" prop="inspectors">
        <el-input
          v-model="searchFormParams.inspectors"
          placeholder="请输入姓名"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="责任部门" prop="deptId">
        <el-cascader
          v-model="searchFormParams.dutyDeptId"
          :options="deptTree"
          :props="{
            value: 'value',
            label: 'label',
            emitPath: false,
            checkStrictly: true
          }"
          clearable
          placeholder="请选择责任部门"
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="整改部门" prop="deptId">
        <el-cascader
          v-model="searchFormParams.issueDeptId"
          :options="deptTree"
          :props="{
            value: 'value',
            label: 'label',
            emitPath: false,
            checkStrictly: true
          }"
          clearable
          placeholder="请选择整改部门"
          class="!w-[200px]"
        />
      </el-form-item>

      <el-form-item label="安全信息内容" prop="questionTitle">
        <el-input
          v-model="searchFormParams.questionTitle"
          placeholder="请输入安全信息"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>

      <el-form-item label="检查日期" prop="planDate">
        <el-date-picker
          class="!w-[240px]"
          v-model="timeRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>


      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="pageLoading"
          @click="onSearch(tableRef)"
        >
          搜索
        </el-button>
        <el-button
          :icon="useRenderIcon(Refresh)"
          @click="handleReset"
        >
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- table bar 包裹  table -->
    <PureTableBar title="整改通知书列表" :columns="columns" @refresh="onSearch(tableRef)">

      <!-- 表格操作栏 -->
      <template #buttons>
        <el-button
          type="danger"
          :icon="useRenderIcon(Delete)"
          @click="handleBulkDeleteWithPermission(tableRef)"
        >
          批量删除
        </el-button>

      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          border
          ref="tableRef"
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="pageLoading"
          :size="size"
          adaptive
          :data="dataList"
          :columns="dynamicColumns"
          :default-sort="defaultSort"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="getReformMainList"
          @page-current-change="getReformMainList"
          @sort-change="onSortChanged"
          @selection-change="
            rows => (multipleSelection = rows.map(item => item.reformId))
          "
        >
          <template #operation="{ row }">

            <!-- 根据 reformStatus 动态渲染按钮 -->
            <template v-if="row.reformStatus">
              <el-button
                v-if="row.reformStatus === '1'"
                class="reset-margin"
                link
                type="warning"
                :size="size"
                :icon="useRenderIcon(DocumentChecked)"
                @click="openMeasureModal(row)"

              >
                审核措施
              </el-button>
              <el-button
                v-if="row.reformStatus === '7'"
                class="reset-margin"
                link
                type="warning"
                :size="size"
                :icon="useRenderIcon(DocumentChecked)"
                @click="openMeasureModal(row)"

              >
                审核整改效果
              </el-button>
              <el-button
                v-if="row.reformStatus === '2' || row.reformStatus === '6'"
                class="reset-margin"
                link
                type="primary"
                :size="size"
                :icon="useRenderIcon(Upload)"
                @click="openMeasureModal(row)"
              >
                执行整改
              </el-button>
              <el-button
                v-if="row.reformStatus === '3' || row.reformStatus === '5'"
                class="reset-margin"
                link
                type="success"
                :size="size"
                :icon="useRenderIcon(SetUp)"
                @click="openMeasureModal(row)"


              >
                制定措施
              </el-button>
              <el-button
                v-if="row.reformStatus === '4'"
                class="reset-margin"
                link
                type="info"
                :size="size"
                :icon="useRenderIcon(View)"
                @click="openMeasureModal(row)"
              >
                详情
              </el-button>
            </template>
          </template>
          <template #problemDetail="{ row }">
            <el-link type="primary" @click="openDetail(row)">
              {{ stripHtmlTagsExceptImages(row.problemDetail) }}

            </el-link>
          </template>

          <template v-slot:questionTitle="{ row }">
            <!-- 根据 isShareReport 判断显示内容 -->
            <template v-if="row.isShareReport === 'F'">
              <span>直接下发-无关联信息</span>
            </template>
            <template v-else>
              <el-link
                type="primary"
                @click="handleSafetyInfoClick(row.relatedQuestionId)"
                style="cursor: pointer"
              >
                {{ row.problemTittle }}
              </el-link>
            </template>
          </template>
        </pure-table>
      </template>


    </PureTableBar>

    <reformMain-measure-modal
      v-model="modalVisible"
      :type="opType"
      :row="opRow"
      @success="getReformMainList"
    />

    <reformMain-detail-modal
      v-model="detailVisible"
      :row="detailRow"
      @success="onSearch"
    />

    <!-- 新增 inspectionCheck 详情弹窗 -->
    <InspectionCheckDetailModal
      v-model="inspectionCheckDetailVisible"
      :row="inspectionCheckDetailData"
      @success="onSearch"
    />
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>


